<?php
require_once "indexdb.php";
require_once "ActiveRecord.php";
require_once "mcache.php";

class Dispatcher
{
	protected $filtermap = array();
	protected $data;
	protected $conf;
	protected $qu;
	private $caches =array();
	public function __construct($conf)
	{
		$this->conf = $conf;
		$this->qu = array();
	}
	
	public function setData($data)
	{
		$this->data = json_decode($data,true);
		//调整下数据格式这里，去掉原来复杂的二维数组结构
		if (!empty($this->data['data']) && is_array($this->data['data']))
		{
			$this->data = $this->data['data'];
		}
	}
	
	//$data是原始数据，如果不需要用可以直接使用$this->data是已解释过的
	public function parse($data)
	{
		///todo 
	}
	
	private function getCacheHandle($app)
	{
		if(empty($this->caches[$app]))
		{
			$this->caches[$app] = new MCache($this->conf['mcache'][$app]);
		}
		
		return $this->caches[$app];
	}
	
	protected function getCache($k,$app="r")
	{
		$cache = $this->getCacheHandle($app);
		return $cache->get("$app-$k");
		///todo
	}
	
	protected function setCache($k,$v,$app = 'r',$t=86400)
	{
		$cache = $this->getCacheHandle($app);
		//return $cache->setCache("$app-$k",$v,$t);
		return $cache->set("$app-$k",$v,$t);
	}
	
	protected  function delete($k,$app)
	{
		$cache = $this->getCacheHandle($app);
		return $cache->delete("$app-$k");
		///todo
	}
	
	//根据用户条件过滤回调决定数据是否下发到指定队列
	public function dispatch($queue,$data)
	{
		foreach($this->filtermap as $q => $f)
		{
			//NULL 为白名单全部通过,filter为回调函数，用于检查是否满跳进入下发队列的条件
			if($f == NULL || call_user_func($f,$this->data))
			{
				//echo "dispatch to queue $q\n";
				$queue->pput($data,$q);
			}
		}
	}
	
	//添加分发过滤条件映射关系
	public function setFilter($q,$clb)
	{
		$this->filtermap[$q] = $clb;
	}
	
	
}
